/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainFrame.java
 *
 * Created on Dec 11, 2009, 5:49:47 AM
 */

package client;
import IO.*;
import java.util.Timer;
import java.util.TimerTask;
import Network.NetworkClient;
import java.awt.BorderLayout;
import java.awt.Color;
import java.io.File;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.xml.parsers.ParserConfigurationException;
/**
 *
 * @author trang
 */

class UserInfo {
  public static String name="";
  public static String id="01";
  public static String dob="";

  public UserInfo(String u, String p,String d) {
    name = u;
    id = p;
    dob = d;
  }
}

public class MainFrameClient extends BaseForm {
 //   public StudentInfo info = new StudentInfo();
    static String name="";
    public static String id="";
    public static String dob="";
    public int indexQuestion = 0;
    public List<ClientAnswer> answerList = new ArrayList<ClientAnswer>();
    public List<Question> questionList = new ArrayList<Question>();

    public boolean isConnected = false;

    protected NetworkClient client = null;



    //For timer
    public int counter;

    public ClientTimerTask task;
    public Timer timer;

    public class ClientTimerTask extends TimerTask
    {
        /**
         * duration of exam calculated by seconds
         */
        int duration;


        ClientTimerTask(int duration)
        {
            this.duration = duration;
        }

        public void run()
        {
            
            duration--;
            int hour = duration/3600;
            int minute = (duration - hour*3600) / 60;
            int second = duration - hour*3600 - minute*60;
            
            String timeString = String.valueOf(hour) +  ":" + String.valueOf(minute);
            if(!client.checkConnection())
            {
                JOptionPane.showMessageDialog(new JDialog(), "Disconnect to server");
                lbStatus.setText("Disconnectted");
                timer.cancel();
            }
            if(duration < 60)
            {
                timeString = String.valueOf(duration);
            }

            if(duration == 60)
            {
                //show message
                //JOptionPane.showMessageDialog(new JDialog(), "1 minutes remain");
                lbStatus.setText("1 minute remain, plz hurry");

            }
            else if(duration == 0)
            {
 //               timeString+= ":" + String.valueOf(second);
                
                
                onSubmit(id, name);
                timer.cancel();
                client.exam.stop =true;
            }


            lbTime.setText(timeString);

        }

    }



    public void onSubmit(String id, String name)
    {
        if(client == null)
            return;
        client.Submit(id, name, this);

    }

    public void setLabelStatus(String msg)
    {
        lbStatus.setText(msg);
    }




    ButtonGroup group = new ButtonGroup();
    public int buttonItems=0;//so luong item trong group button trc khi minh add vao
    /** Creates new form MainFrame */
    public MainFrameClient() {
        initComponents();
    }
        
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        buttonGroup2 = new javax.swing.ButtonGroup();
        buttonGroup3 = new javax.swing.ButtonGroup();
        buttonGroup4 = new javax.swing.ButtonGroup();
        buttonGroup5 = new javax.swing.ButtonGroup();
        panQuestions = new javax.swing.JPanel();
        btnBack = new javax.swing.JButton();
        btnSubmit = new javax.swing.JButton();
        btnNext = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        Ques = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        lbTime = new javax.swing.JLabel();
        lbStatus = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        studentInfo = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Client");

        javax.swing.GroupLayout panQuestionsLayout = new javax.swing.GroupLayout(panQuestions);
        panQuestions.setLayout(panQuestionsLayout);
        panQuestionsLayout.setHorizontalGroup(
            panQuestionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 474, Short.MAX_VALUE)
        );
        panQuestionsLayout.setVerticalGroup(
            panQuestionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 142, Short.MAX_VALUE)
        );

        btnBack.setText("<<");
        btnBack.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBackActionPerformed(evt);
            }
        });

        btnSubmit.setText("Submit");
        btnSubmit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSubmitActionPerformed(evt);
            }
        });

        btnNext.setText(">>");
        btnNext.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNextActionPerformed(evt);
            }
        });

        Ques.setColumns(20);
        Ques.setEditable(false);
        Ques.setRows(5);
        jScrollPane1.setViewportView(Ques);

        jLabel1.setText("Time left :");

        lbTime.setText("0:00");

        jMenu1.setText("File");
        jMenu1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMenu1MouseClicked(evt);
            }
        });

        jMenuItem1.setText("Load configuration");
        jMenuItem1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMenuItem1MouseClicked(evt);
            }
        });
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        studentInfo.setText("Student info");
        studentInfo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                studentInfoActionPerformed(evt);
            }
        });
        jMenu1.add(studentInfo);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Exam");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 474, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(panQuestions, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(87, 87, 87)
                        .addComponent(btnBack)
                        .addGap(18, 18, 18)
                        .addComponent(btnNext)
                        .addGap(72, 72, 72)
                        .addComponent(btnSubmit, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addComponent(lbStatus)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 276, Short.MAX_VALUE)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27)
                .addComponent(lbTime, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(19, 19, 19))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(lbTime)
                    .addComponent(lbStatus))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panQuestions, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSubmit)
                    .addComponent(btnBack, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
                    .addComponent(btnNext))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
/**
 * To help you show one question
 * @param indexQues  : index of  question that you want to show
 */
    private void ShowQuestion(int indexQues)
    {
        try
        {
           Ques.setText("");
           panQuestions.removeAll();
       
           Ques.append("    Question "+String.valueOf(indexQues+1)+":");
           Ques.append(questionList.get(indexQues).getStatement()+"\n");

           //Add radio for user to choose
           int numChoices = questionList.get(indexQues).getNumberOfChoice();
           int x = 12;
           int y = 302; // Moi lan co 1 lua chon la +y 20
           panQuestions.setLayout(new BoxLayout(panQuestions, BoxLayout.PAGE_AXIS));
           String anQuestion = answerList.get(indexQues).getAnswerString();
           for(int h = 0;h<numChoices;h++)
           {
               JRadioButton ra = new JRadioButton(questionList.get(indexQues).getOneChoice(h));               
               ra.setLocation(x, y);
               y=y+20;
               group.add(ra);
               panQuestions.add(ra,h);
               if(questionList.get(indexQues).getOneChoice(h).equals(anQuestion)==true)
               {
                    group.setSelected(ra.getModel(), true);
               }
               validate();                              
           }
            // kiem tra neu no da co trong list answer thi set selection cho no  //** chua xong
           
        }
        catch(Exception e)
        {
            
        }
    }

    private String getSelectedFromButton()
    {
        try
        {
        int index =0;
        char start = 'a';
        for (Enumeration e=group.getElements(); e.hasMoreElements(); )
        {
            JRadioButton b = (JRadioButton)e.nextElement();
            if (b.getModel() == group.getSelection())
            {
                answerList.get(indexQuestion).setAnswerString(b.getText());//lưu thông tin câu trả loi
                int inChoice = (int)start+index-buttonItems;
                //convert back to string
                char choice = (char)inChoice;
                return String.valueOf(choice);
            }
            else
            {
                index++;
            }
        }       
        }
        catch(Exception e)
        {

        }
         return "";
    }

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed

//        try {
            JFileChooser fc = new JFileChooser();

            int returnVal = fc.showOpenDialog(MainFrameClient.this);
            String filename = "";
            String path = "";
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                //This is where a real application would open the file.
                filename = file.getName();
                path = file.getAbsolutePath();
                System.out.print(file.getAbsolutePath());
                System.out.print("Opening: " + file.getName());
                
                // Khang 's
                try
                {

                    List<String> listInfos = IOFIle.readFileConfigure(path);
                    client = new NetworkClient(listInfos.get(0), Integer.valueOf(listInfos.get(1)));
                    client.connect(this);

                }
                catch(Exception e){
                    System.out.println(""+e.toString());
                }

                // END OF KHANG 's
            } else {
                System.out.print("Open command cancelled by user");
            }
            //     }

            // Read file
//            IO.Exam xml = new IO.Exam(path);
            IO.Exam xml = client.exam;

            
      //Coi như minh da nhan dc listQuestion tu server 
            
//        } catch (ParserConfigurationException ex) {
//            Logger.getLogger(MainFrameClient.class.getName()).log(Level.SEVERE, null, ex);
//        }
            //Doc du lieu vao

    }//GEN-LAST:event_jMenuItem1ActionPerformed
    

    private void jMenuItem1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenuItem1MouseClicked
           
            javax.swing.JFileChooser file = new javax.swing.JFileChooser();
            file.showDialog(this.getComponent(1), null);
            File f = file.getSelectedFile();
        
    }//GEN-LAST:event_jMenuItem1MouseClicked

    private void jMenu1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenu1MouseClicked
        // TODO add your handling code here:
       JLabel la2 = new JLabel("Nguyen u");
       la2.setLocation(140, 40);
        this.getContentPane().add(la2);
        this.setVisible(true);
        repaint();    
      
    }//GEN-LAST:event_jMenu1MouseClicked

    private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNextActionPerformed
        // Next
    //kt xem index hien tai cua no : neu no lon nhat thi ko next nua
        int numQues = answerList.size();
        String an = getSelectedFromButton();
        answerList.get(indexQuestion).setAnswer(an);

        if(indexQuestion>(numQues-1) || indexQuestion==(numQues-1) )
        {
            btnNext.disable();
            return ;            
        }
        else
        {
            btnNext.enable();
            Ques.setText("");
 //           panQuestions.removeAll();
            buttonItems = group.getButtonCount();
            ShowQuestion(++indexQuestion);
        }
    }//GEN-LAST:event_btnNextActionPerformed

    private void btnBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBackActionPerformed
        // Back
      //kt xem index hien tai cua no : neu no nho nhat thi ko back nua
        int numQues = answerList.size();
        String an = getSelectedFromButton();
        answerList.get(indexQuestion).setAnswer(an);
        if(indexQuestion==0)
        {
            btnBack.disable();
            return ;
        }
        else
        {
            btnBack.enable();
            Ques.setText("");
   //         panQuestions.removeAll();
            buttonItems = group.getButtonCount();
            
            ShowQuestion(--indexQuestion);
        }

    }//GEN-LAST:event_btnBackActionPerformed

    private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSubmitActionPerformed
        //  Submit

        //phai kiem tra xem ,neu no co check thi minh moi edit trong answer list.neu ko thi thoi
        String an = getSelectedFromButton();
        answerList.get(indexQuestion).setAnswer(an);

        IOFIle.WriteAnswersToFile(id, answerList);
        client.Submit(id, name,this);
    }//GEN-LAST:event_btnSubmitActionPerformed

    private void studentInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_studentInfoActionPerformed
        // TODO add your handling code here:
        try
        {
            List<String> listInfo = IOFIle.readFileStudent("D:\\studentInfo.txt");
            if(listInfo.size()!=0)
            {
                StudentInfo info = new StudentInfo(listInfo.get(0),listInfo.get(1),listInfo.get(2));
                info.show();
            }
            else
            {
                StudentInfo info = new StudentInfo();
                info.show();
            }
            
        }
        catch(Exception e)
        {
            
        }
    }//GEN-LAST:event_studentInfoActionPerformed

    /**
     * start the exam
     */
    public void beginExam()
    {

        IO.Exam xml = client.exam;
        if(xml == null)
        {
            //JOptionPane.showMessageDialog(new JDialog(), "No exam today");
            lbStatus.setText("No exam today");
            return;
        }
        int numQues = xml.getTotalQuestion();
        for(int i=0;i<numQues;i++)
        {
            //Add tat ca answer ma chua co cau tra loi vao danh sach list answer
            ClientAnswer an = new ClientAnswer(i, "");
            answerList.add(i, an);
            questionList.add(xml.getQuestion(i));
        }
        ShowQuestion(indexQuestion);

        lbStatus.setText("Exam is beginning");
        // timer
        timer = new Timer();
        timer.schedule(new ClientTimerTask(1*Integer.parseInt(xml.getLength())), 0,1000);

    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainFrameClient().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea Ques;
    private javax.swing.JButton btnBack;
    private javax.swing.JButton btnNext;
    private javax.swing.JButton btnSubmit;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.ButtonGroup buttonGroup3;
    private javax.swing.ButtonGroup buttonGroup4;
    private javax.swing.ButtonGroup buttonGroup5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lbStatus;
    private javax.swing.JLabel lbTime;
    private javax.swing.JPanel panQuestions;
    private javax.swing.JMenuItem studentInfo;
    // End of variables declaration//GEN-END:variables


}


////Probs :
//Tắt app thi no ko nho dc cai dua moi dang nhap luc trc la ai
